//
//  AppDelegate.swift
//  ManBetX
//
//  Created by Fullen on 3/16/20.
//  Copyright © 2020 Fullen. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import Eagleeyes.DevicePrint


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    //网络环境监听控件的初始化
    let reachability = Reachability()!
    
    // 横竖屏
    var blockRotation: UIInterfaceOrientationMask = .portrait{
        didSet{
            if blockRotation.contains(.portrait){
                //强制设置成竖屏
            UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
            }else{
                //强制设置成横屏
            UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
                
            }
        }
    }
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        DevicePrint.start(DefaultKey.EAGLEEYES_TOKEN)
        let defaults = UserDefaults.standard
        defaults.set("d11", forKey: DefaultKey.SITE_ID)
        //mt 由http改https 2018.6.4
        defaults.set("https", forKey: DefaultKey.DOMAIN_SCHEME)
        defaults.set(GlobalInfo.apiDomain, forKey: DefaultKey.USER_DOMAIN)
//        print("API:\(GlobalInfo.apiDomain) ========== Game.json:\(GlobalInfo.resDomain)  USER_DOMAIN:\(UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN))")
        
        //网络环境的监听方法
        networkStatusListener()
        
        return true
    }

   
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        
        let config: CountlyConfig = CountlyConfig()
         config.appKey = kCountlyAppKey
         config.host = kCountlyHost
         #if DEBUG
         config.enableDebug = true
         #endif
         config.features = [CLYCrashReporting, CLYAutoViewTracking]
         Countly.sharedInstance().start(with: config)
        
         IQKeyboardManager.shared.enable = true
         IQKeyboardManager.shared.shouldResignOnTouchOutside = true
         IQKeyboardManager.shared.enableAutoToolbar = false
        
        //设置ip数组从plist中获取
        isTest = GlobalInfo.mainIsTest
        if(isTest){
            kMainIpArray = Array<String>.init()
            kMainIpArray.append(GlobalInfo.doMainTest)
        }else{
            kMainIpArray = GlobalInfo.mainIpArray
        }
        if let mainTabBarController = self.window?.rootViewController as? MainTabBarController {
            if var topController = mainTabBarController.selectedViewController {
                while let presentedViewController = topController.presentedViewController {
                    topController = presentedViewController
                }
                
                if topController is UINavigationController {
                    if let gameView = (topController as! UINavigationController).visibleViewController as? GameWebViewBaseController {
                        if gameView.disappearing {
                            
                            UIApplication.shared.setStatusBarHidden( (gameView.navigationController?.isNavigationBarHidden)!, with: .fade)
                            return UIInterfaceOrientationMask.portrait
                        } else {
                            UIApplication.shared.setStatusBarHidden((gameView.navigationController?.isNavigationBarHidden)!, with: .fade)
                           let isWbyzt =  UserDefaults.standard.bool(forKey:DefaultKey.IS_WBYZT)
                            if isWbyzt == true{
                                return UIInterfaceOrientationMask.landscape
                            }
                            return UIInterfaceOrientationMask.all
                        }
                    } else {
                        return UIInterfaceOrientationMask.portrait
                    }
                }
            }
            return UIInterfaceOrientationMask.portrait
        }
        return UIInterfaceOrientationMask.portrait
    }
    
    
    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        print(url)
        if url.path == "/reg" {
            let queries = url.queryItemsDictionary
            if let action = queries["action"]{
                if action == "reg_success" {
                    if let username = queries["username"], let password = queries["password"] {
                        if let decryptedPassword = RSAHelper.decrypt(password) {
                            if let loginNavigationViewController = UIHelper.getTopController() as? LoginNavigationViewController{
                                    UserDefaults.standard.set(username, forKey: DefaultKey.USER_LOGIN_NAME)
                                    
                                    loginNavigationViewController.loginViewController?.shouldNotEmptyPasswordField = true
                                    loginNavigationViewController.loginViewController?.accountTextField.text = username
                                    loginNavigationViewController.loginViewController?.passwordTextField.text = decryptedPassword
                                    loginNavigationViewController.popViewController(animated: true)
                            }
                        }
                    }
                }
            }
        }
        return true
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
          completionHandler(UIBackgroundFetchResult.newData);
      }
    
    
    
    //启动当前网络环境开始
    func networkStatusListener() {
        
        // 1、设置网络状态消息监听 2、获得网络Reachability对象
        NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged),name: Notification.Name.reachabilityChanged,object: reachability)
        do{
            // 3、开启网络状态消息监听
            try reachability.startNotifier()
        }catch{
            print("could not start reachability notifier")
        }
    }
    
     // 主动检测网络状态
    @objc func reachabilityChanged(note: NSNotification) {
        
        let reachability = note.object as! Reachability // 准备获取网络连接信息
        if reachability.isReachable { // 判断网络连接状态
            print("网络连接：可用")
            // 网络可用，放出通知
            NotificationCenter.default.post(name: NSNotification.Name(NotifationKey.netWorkUsable.rawValue), object: nil)
            
            if reachability.isReachableViaWiFi {
                // 判断网络连接类型
            } else {
                 print("连接类型：移动网络")
            }
        } else {
            print("网络连接：不可用")
//            DispatchQueue.main.async {
//                // 不加这句导致界面还没初始化完成就打开警告框，这样不行
//            }
        }
    }
}

